﻿/*
*此文件中包括如下功能函数：
*GetBodyDocument():获取最顶层的document
*DelayTimeFunction(fRef, mDelay):延迟执行方法
*SetDisabledByID(eventOriginId,disabled)：设置控件是否可用
*ShowLoading(loadingId,eventOriginId):显示加载动画
*HideLoading(divId):隐藏加载动画
*SetFocus(ctlid,empty):定位焦点
*document_onkeydown():键盘敲击事件
*ValidityCheck():VM中公用的验证函数
*GetBasePath()：获取文件的根目录
*toAnalysisByFC(modelName)：跳转到分析窗体
*toUseLast():沿用数据
*ExportExcel():导出Excel
*RefreshIndex(controlName,paneID):刷新标签页
*SelectGridPosition(position):Grid行定位
*SetMonitorInfoSelfCode(selectedNodeSelfCode):为MonitorSetUpCard页中标志selfCode与真实selfCode赋值
*SetNodeTextBox(NodeSelfCode,NodeID,NodeText):为树相关文本框附值
*ModifyPwd():弹出修改密码
*UnKeyDown(toolID):去除控件的按键事件
*SessionTimeOut(win):session超时处理
*importCSSFile():导入CSS文件
*CheckGridselectAll():复选框列全选
*CheckGridClick(checkbox,controllerName,formName,tabName):复选框列单击
*CheckGridTest():复选框列测试,取得所有选中框的ID（临时）
*/
//获取最顶层的document
GetBodyDocument=function ()
{
    var bodyDoc;
    bodyDoc = window.parent.parent.parent.parent.parent.parent.document;
    return bodyDoc;
}

//延迟执行方法
var _st = window.setTimeout;
DelayTimeFunction = function(fRef, mDelay) 
{
    if(typeof fRef == 'function')
    {  
        var argu = Array.prototype.slice.call(arguments,2);  
        var f = (function(){ fRef.apply(null, argu); });  
        return _st(f, mDelay); 
    } 
    return _st(fRef,mDelay);
}

//设置控件是否可用
var StaticOriginId;
SetDisabledByID=function(eventOriginId,disabled)
{
    var eventOrigin = dojo.byId(eventOriginId);
    if(eventOrigin)
    {
        StaticOriginId=eventOriginId;
        if(disabled)
        {
            eventOrigin.disabled='disabled';
        }
        else
        {
            eventOrigin.disabled='';
        }
    }
}
GetById=function(id,document)
{
    var obj=dojo.byId(id,document);
    if(!obj)
    {
        if(this!=this.parent)
        {
           obj=GetById(id,this.parent.document)
        }
    }
    return obj
}
//显示加载动画
function ShowLoading(loadingId,eventOriginId)
{
    var loadingDiv = GetById(loadingId); 
    if(loadingDiv)
    {
        loadingDiv.style.display = '';
        if(eventOriginId)
        {
            SetDisabledByID(eventOriginId,true);
        }
    }
};

//隐藏加载动画
function HideLoading(divId)
{
    DelayTimeFunction(SubHideDiv,0,divId);
}
SubHideDiv =function(divId)
{
    var hideDiv = GetById(divId);
    if(hideDiv)
    {
        hideDiv.style.display = 'none';
        SetDisabledByID(StaticOriginId,false);
    }
}

//定位焦点
SetFocus = function (ctlid,empty)
{
	if (ctlid!="" && dojo.byId(ctlid) != undefined )
	{
		dojo.byId(ctlid).focus();
		if(!empty)
		{//如果无内容则不执行select(),例如按钮。
		    dojo.byId(ctlid).select();
		}
	}
}

//键盘敲击事件
document_onkeydown=function() 
{
	var src_obj = window.event.srcElement;
	if(src_obj.type==undefined)
	{
	    return;
	}
	if (window.event.keyCode == 13)
	{
		if (src_obj.type == "text"||src_obj.type =="password")//20090409
		{
			window.event.keyCode = 9;
		}
	}
}


//VM中公用的验证函数
function ValidityCheck()
{
    var errId="";
	var errMessage = "";
	var isOk=true; 
	var arr = new dojox.collections.ArrayList();  
    arr.add('dijit.form.ValidationTextBox');
    arr.add('dijit.form.NumberTextBox');
    arr.add('dijit.form.ComboBox');
    arr.add('dijit.form.SimpleTextarea');
    arr.add('dijit.form.DateTextBox');
	dijit.registry.filter
	(
	    function(widget)
	    {
	        //return (widget.declaredClass=="dijit.form.ValidationTextBox")||(widget.declaredClass=="dijit.form.NumberTextBox")||(widget.declaredClass=="dijit.form.ComboBox")||(widget.declaredClass=="dijit.form.SimpleTextarea")?true:false;
	        return(arr.contains(widget.declaredClass));
	    }
	).forEach(
	    function(widget)
	    {
	        if(!widget.isValid())
		    { 	
			    if(errMessage == "")
				    errMessage += widget.invalidMessage
			    else
				    errMessage += "<br/>" + widget.invalidMessage;
				if(errId=="")
				   errId= widget.id;
			    isOk=false; 
			    return false;
		    }
	    }
	); 
	if(isOk == false)
	{
		//隐藏进度条
		HideLoading('divCovering');
		Ext.MessageBox.alert('系统信息',errMessage,function(){SetFocus(errId);});
    }
	return isOk; 
};

//获取文件的根目录
GetBasePath=function ()
{
    var basePath= document.location.pathname.substring(document.location.pathname.indexOf('/')+1) ;
    basePath= basePath.substring(0,basePath.indexOf('/'));
    return basePath;
}

//跳转到分析窗体
toAnalysisByFC= function(modelName)
{
    window.open('/'+GetBasePath()+'/Chart/FusionCharts.castle?tableName='+modelName,'charForm');
}

//沿用数据
toUseLast= function()
{   
    var grid = Ext.getCmp("MVCGRID");
    var record = grid.getSelectionModel().getSelected();
    var row = grid.getSelectionModel().getSelections();
	if(record==null)
	{
		Ext.MessageBox.alert('系统消息','请选择要编辑的行！');			
	}
	else if(row.length==1)
	{
	    var rowValue = record.get("EditCol");
	    var parts = rowValue.split('#');
        ShowLoading('divCovering');
        AjaxPost(parts[1],"UseLast",parts[3],parts[5],parts[4]);
	}else
	{
		Ext.MessageBox.alert('系统消息','请选择要编辑的行！');
	}
}

//导出Excel
ExportExcel= function(modelName)
{
    //window.open('/'+GetBasePath()+'/Excel/ExportExcel.castle?modelName='+modelName,'ExcelForm');
    window.location.href='/'+GetBasePath()+'/Excel/ExportExcel.castle?modelName='+modelName;
}

//刷新标签页
RefreshIndex=function(controlName,paneID)
{
    var modelName=paneID.substring(3);
    AjaxPost(controlName,'ModelIndex','frm'+controlName,'currentModelName='+modelName,'TabBodyContainer');
}


//grid行定位
SelectGridPosition=function(position)
{
    var grid = Ext.getCmp("MVCGRID");
    if(grid==null)
    {
        return;
    }
    var store = grid.getStore();
    if(store==null)
    {
        return;
    }
    store.on
    (
        'load',
        renderFunc=function()
        {
            grid.getSelectionModel().selectRow(position);
            store.un('load',renderFunc);
        }
    );
}


//为MonitorSetUpCard页中标志selfCode与真实selfCode赋值
SetMonitorInfoSelfCode=function(selectedNodeSelfCode,id,text,canalBelong)
{
    var factSelfCode=dojo.byId('IDTOX.MonitorSelfCode');
    var flagSelfCode=dojo.byId('IDTOXMonitorSelfCode');
    if(factSelfCode!=undefined && factSelfCode!=null)
    {
        factSelfCode.value= selectedNodeSelfCode;
    }
    if(flagSelfCode!=undefined && flagSelfCode!=null)
    {
        flagSelfCode.value= selectedNodeSelfCode;
    }
    var monitorCanalBelong=dojo.byId('IDTOX.CanalName');
    if(monitorCanalBelong)
    {
        monitorCanalBelong.value=canalBelong;
    }
}
//为树相关文本框附值
SetNodeTextBox=function(NodeSelfCode,NodeID,NodeText)
{
    var txtNodeText=dojo.byId('IDTOX.DepartmentType');
    var txtNodeID=dojo.byId('IDTOX.DepartmentID');
    if(txtNodeText!=undefined && txtNodeText!=null)
    {
        txtNodeText.value= NodeText;
    }
    if(txtNodeID!=undefined && txtNodeID!=null)
    {
        txtNodeID.value= NodeID;
    }
    AccordSelfCode(NodeSelfCode);
}


//弹出修改密码
ModifyPwd= function()
{
    dijit.byId('ModifyPwdContent').show();
    dojo.byId('oldPwd').value="";
    dojo.byId('newPwd').value="";
    dojo.byId('newPwdPardden').value="";
}

//去除控件的按键事件
UnKeyDown=function(toolID)
{
	var tool=dojo.byId(toolID);
	if(tool)
    {
        tool.onkeydown=function(){};
        tool.onkeypress=function(){};
    }
}

//session超时处理
SessionTimeOut = function(win) 
{
    if(win.parent==win)
    {
        if(win.name=='IrrBasicInfoForm'||win.name=='IrrSummary'||win.name=='OrganForm'||win.name=='charForm'||win.name=='ExcelForm')
        {
            Ext.MessageBox.alert('错误提示','页面超时,窗口将自动关闭。',function(){win.close();});
        }
        else
        {
            Ext.MessageBox.alert('错误提示','页面超时,请重新登录！',function(){win.location= '/'+GetBasePath()+'/home/index.castle';});
        }
    }
    else
    {
        Login(win.parent);
    }
}
//导入CSS文件
function importFile(path,type,title){
    var s,i;
    if(type=="js"){
        var ss=document.getElementsByTagName("script");
        for(i=0;i<ss.length;i++){
            if(ss[i].src && ss[i].src.indexOf(path)!=-1)return ss[i];
        }
        s=document.createElement("script");
        s.type="text/javascript";
        s.src=path;
    }else if(type=="css"){
        var ls=document.getElementsByTagName("link");
        for(i=0;i<ls.length;i++){
            if(ls[i].href && ls[i].href.indexOf(path)!=-1)return ls[i];
        }
        s=document.createElement("link");
        s.rel="alternate stylesheet";
        s.type="text/css";
        s.href=path;
        s.title=title;
        s.disabled=false;
    }
    else return;
    var head=document.getElementsByTagName("head")[0];
    head.appendChild(s);
    return s;
} 
//复选框列全选
function CheckGridselectAll(checkbox,controllerName,formName)
{
    var checkBoxes=document.getElementsByName('chbGridCheckColumn');
    dojo.forEach
    (
        checkBoxes,
        function(checkBox)
        {
            checkBox.checked =checkbox.checked;
        }
    )
    AjaxPost(controllerName,'CheckGridClidk',formName,'flag='+checkbox.checked)
}
//复选框列单击
function CheckGridClick(checkbox,primaryKey,controllerName,formName)
{
    AjaxPost(controllerName,'CheckGridClidk',formName,primaryKey+'&flag='+checkbox.checked)
}

//复选框列测试,取得所有选中框的ID（临时）
function CheckGridTest()
{
    var checkBoxes=document.getElementsByName('chbGridCheckColumn');
    var checkedPK='';
    dojo.forEach
    (
        checkBoxes,
        function(checkBox)
        {
            if(checkBox.checked)
            {
                checkedPK+=checkBox.id;
            }
        }
    )
    Ext.MessageBox.alert('系统信息',checkedPK,function(){AjaxPost('MonitorSetUp','CheckGridTest','frmMonitorSetUp')});
}

function Refush(findNodeSelfCode)
{
    var canalTree = Ext.getCmp("CanalTree");
    canalTree.loader.load(canalTree.root,a=function()
    {
        var currentSelfCode='';
        if(findNodeSelfCode!='')
        {
            canalTree.on
            (
                'expandnode',locationTreeNode=function(node)
                {
                    debugger;
                    currentSelfCode=currentSelfCode+findNodeSelfCode.substr(currentSelfCode.length,4)
                    var parentNode=node.findChild('selfCode',currentSelfCode);
                    if(parentNode)
                    {
                        if(currentSelfCode!=findNodeSelfCode)
                        {
                            parentNode.expand();
                        }
                        else
                        {
                            parentNode.select();
                            canalTree.removeListener('expandnode',locationTreeNode);
                            currentSelfCode='';
                        }
                    }
                }
                
            );
        }
        canalTree.root.expand();
    });
}

//canalTree.on('append',locationTree=function(tree, parentNode, newNode,index)
//    {
//        if(newNode.attributes.selfCode==currentSelfCode)
//        {
//            debugger;
//            if(currentSelfCode!=findNodeSelfCode)
//            {
//                newNode.expand();
//                currentSelfCode=currentSelfCode+findNodeSelfCode.substr(currentSelfCode.length,4)
//            }
//            else
//            {
//                newNode.select();
//                canalTree.removeListener('append',locationTree);
//                currentSelfCode='';
//            }
//        }
//    }
//        );
